import glob
import sys
import os
import time
import numpy as np
import cv2


path='D:\\vcode\\'
pathOut='D:\\vcode2\\'
def test1():
    im = cv2.imread('D:\\vcode\\3p7e.jpg')
    im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    # 二值化
    th1 = cv2.adaptiveThreshold(im, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 21, 1)
    cv2.imwrite('D:\\vcode\\3p7e-01.jpg', th1)
    # edges = cv2.Canny(th1, 30, 70)
    # cv2.imshow('二值化', th1)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()

def test2(fn):
    fn1, fn2 = fn.split(".")[:2]
    #二值化图片，并且线降噪
    img = cv2.imread(path+fn)
    h, w = img.shape[:2]
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # 灰值化
    # cv2.imwrite('D:\\vcode\\3p7e-gray.jpg', img)
    # 二值化
    img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 1)
    # cv2.imwrite('D:\\vcode\\3p7e-01.jpg', img)
    # opencv矩阵点是反的
    # img[1,2] 1:图片的高度，2：图片的宽度
    xx=225
    for y in range(1, w - 1):
        for x in range(1, h - 1):
            count = 0
            if img[x, y - 1] > xx:
                count = count + 1
            if img[x, y + 1] > xx:
                count = count + 1
            if img[x - 1, y] > xx:
                count = count + 1
            if img[x + 1, y] > xx:
                count = count + 1
            if count > 2:
                img[x, y] = 255
    fn_02 = pathOut + fn1 + "02." + fn2
    cv2.imwrite(fn_02, img)

    # kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))  # 定义结构元素
    # kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))  # 定义结构元素
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))  # 定义结构元素
    opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)  # 开运算
    closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)

    cv2.imwrite(pathOut + fn1 + "opening." + fn2, opening)
    cv2.imwrite(pathOut + fn1 + "closing." + fn2, closing)

def test_data():
    test_files = os.listdir("D:\\vcode")
    total = 0
    correct = 0
    for filename in test_files:
        if(filename.endswith(".jpg")):
            print(filename)
            test2(filename)


if __name__ == "__main__":
    test_data()
    # test2('3p7e.jpg')
